package com.orangelife.webservice.service.propFeeReceipt.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;

import org.drools.compiler.lang.dsl.DSLMapParser.mapping_file_return;
import org.mvel2.optimizers.impl.refl.nodes.ArrayLength;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.feeDetail.IFeeDetailService;
import com.orangelife.service.propFeeComm.IPropFeeCommService;
import com.orangelife.service.propFeeComm.model.PropFeeCommDto;
import com.orangelife.service.propFeeOffsetInfo.IPropFeeOffsetInfoService;
import com.orangelife.service.propFeeReceipt.IPropFeeReceiptService;
import com.orangelife.service.propFeeReceipt.model.PropFeeReceiptDto;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.utils.PropertyUtils;
import com.orangelife.utils.StringUtils;
import com.orangelife.webservice.base.BaseService;
import com.orangelife.webservice.base.PageUtils;
import com.orangelife.webservice.service.propFeeReceipt.IPropFeeReceiptWebService;

/*****************************************************************
 * Copyright(C) ORANGELIFE Corporation 2015. All Rights Reserved.
 *****************************************************************/
/*
 * ============================================================== 功能名
 * propFeeReceipt类 的WebService基本作业
 * 
 * @author zhr
 * 
 * @version 1.1.0
 * 
 * @date 2016-12-12 15:47:46
 * ==============================================================
 */
@Service("webservice_propFeeReceipt")
public class PropFeeReceiptWebServiceImpl extends BaseService implements
		IPropFeeReceiptWebService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Resource(name = "propFeeCommService")
	private IPropFeeCommService propFeeCommService;
	@Resource(name = "propFeeReceiptService")
	private IPropFeeReceiptService propFeeReceiptService;
	@Resource(name = "feeDetailService")
	private IFeeDetailService feeDetailService;
	@Resource(name = "propFeeOffsetInfoService")
	private IPropFeeOffsetInfoService propFeeOffsetInfoService;

	@Override
	public Response addPropFeeReceipt(HttpServletRequest servletRequest,
			PropFeeReceiptDto propFeeReceipt) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		propFeeReceipt.setCreateuserID(pageUtils.getBaseSession().getUserID());
		int result = propFeeReceiptService.addPropFeeReceipt(propFeeReceipt);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		return this.normalResp();
	}

	@Override
	public Response editPropFeeReceipt(HttpServletRequest servletRequest,
			PropFeeReceiptDto propFeeReceipt) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(propFeeReceipt.getReceiptID(),
				"receiptID");
		if (error != null) {
			return error;
		}

		/************************************************
		 * 输入参数检查
		 ************************************************/
		// TODO;

		propFeeReceipt.setEdituserID(pageUtils.getBaseSession().getUserID());
		int result = propFeeReceiptService.editPropFeeReceipt(propFeeReceipt);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "修改实体成功");

		return this.normalResp();
	}

	@Override
	public Response deletePropFeeReceipt(HttpServletRequest servletRequest,
			String receiptID) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(receiptID, "receiptID");
		if (error != null) {
			return error;
		}
		int result = propFeeReceiptService
				.deletePropFeeReceiptByLogic(receiptID);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功");

		return this.normalResp();
	}

	@Override
	public Response findPropFeeReceiptByID(HttpServletRequest servletRequest,
			String receiptID) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(receiptID, "receiptID");
		if (error != null) {
			return error;
		}
		try {
			PropFeeReceiptDto propFeeReceipt = propFeeReceiptService
					.findPropFeeReceiptByID(receiptID);

			PropFeeCommDto propFeeCommDto = propFeeCommService
					.findPropFeeCommByID(propFeeReceipt.getCommID());
			propFeeReceipt.setHouseInfos(propFeeCommDto.getComm() + " , "
					+ propFeeReceipt.getHouseInfo());

			map.put("entity", propFeeReceipt);
			map.put("errInfo", "ok");
			map.put("errCode", "0");
			logger.info(pageUtils.getBaseSession().getLoginName() + "在"
					+ pageUtils.getBaseSession().getLoginType() + "端"
					+ new Date() + "时" + "查询实体成功");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();
	}

	@Override
	public Response getAllPropFeeReceipt(HttpServletRequest servletRequest,
			String search, String tsCreate, String pageIndex, String pageSize)
			throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeReceiptService
				.findPropFeeReceiptByPage(tsCreate == null ? null : tsCreate,
						search == null ? null : search,
						pageUtils.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response bauthFindPropFeeReceipt(HttpServletRequest servletRequest,
			List<String> propFeeReceipt) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeReceipt == null || propFeeReceipt.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", propFeeReceiptService
					.bauthfindPropFeeReceipt(propFeeReceipt));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response bauthFindPropFeeReceipts(HttpServletRequest servletRequest,
			Map<String, Object> propFeeReceipt) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeReceipt == null || propFeeReceipt.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils
					.turnToEntity(propFeeReceiptService
							.bauthfindPropFeeReceiptByMap(propFeeReceipt)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response clearCache(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		propFeeReceiptService.clearCache();
		return this.normalResp();
	}

	@Override
	public Response addReceipt(HttpServletRequest servletRequest,
			PropFeeReceiptDto propFeeReceipt) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		try {
			propFeeReceipt.setCreateuserID(pageUtils.getBaseSession()
					.getUserID());
			propFeeReceipt.setDrawer(StringUtils.isBlank(pageUtils
					.getBaseSession().getTrueName()) ? pageUtils
					.getBaseSession().getLoginName() : pageUtils
					.getBaseSession().getTrueName());
			propFeeReceipt.setCreateuser(StringUtils.isBlank(pageUtils
					.getBaseSession().getTrueName()) ? pageUtils
					.getBaseSession().getLoginName() : pageUtils
					.getBaseSession().getTrueName());
			propFeeReceipt.setPmID(pageUtils.getBaseSession().getPmID());
			propFeeReceipt.setAccessToken(pageUtils.getBaseSession().getKey());
			Map<String, Object> result = propFeeReceiptService
					.addPropFeeReceipts(propFeeReceipt);

			logger.info(pageUtils.getBaseSession().getLoginName() + "在"
					+ pageUtils.getBaseSession().getLoginType() + "端"
					+ new Date() + "时" + "添加实体成功");

			map.put("entity", result);
			map.put("errInfo", "ok");
			map.put("errCode", "0");
			logger.info(pageUtils.getBaseSession().getLoginName() + "在"
					+ pageUtils.getBaseSession().getLoginType() + "端"
					+ new Date() + "时" + "查询实体成功");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response findPropFeeReceiptInfo(HttpServletRequest servletRequest,
			String linkID, String type) throws Exception {
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {
			map.put("entity",
					propFeeReceiptService.findPropFeeReceipt(linkID, type));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response nullifyReceipt(HttpServletRequest servletRequest,
			PropFeeReceiptDto propFeeReceipt) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		propFeeReceipt.setEdituserID(pageUtils.getBaseSession().getUserID());
		propFeeReceipt.setEdituser(StringUtils.isBlank(pageUtils
				.getBaseSession().getTrueName()) ? pageUtils.getBaseSession()
				.getLoginName() : pageUtils.getBaseSession().getTrueName());
		propFeeReceipt.setPmID(pageUtils.getBaseSession().getPmID());
		propFeeReceipt.setAccessToken(pageUtils.getBaseSession().getKey());
		Map<String, Object> result = propFeeReceiptService
				.nullifyReceipt(propFeeReceipt);

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		return this.normalResp(result);

	}

	@Override
	public Response getPropFeeReceiptInfo(HttpServletRequest servletRequest,
			String type, String apartmentID, String search, String tsCreate,
			String pageIndex, String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeReceiptService
				.findPropFeeReceiptInfo(type, apartmentID,
						tsCreate == null ? null : tsCreate,
						search == null ? null : search, pageUtils
								.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response getMonthNoReNum(HttpServletRequest servletRequest,
			String rType, String type, String apartmentID, String feeDate,
			String search, String tsCreate, String pageIndex, String pageSize)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		try {

			if (!StringUtils.isBlank(tsCreate)) {
				StringUtils.isTime(tsCreate);
				tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
			}
			/************************************************
			 * 查询列表
			 ************************************************/
			List<Map<String, Object>> list = propFeeReceiptService
					.getMonthNoReNum(rType, type, apartmentID, feeDate,
							tsCreate, search == null ? null : search,
							pageUtils.getiPageIndex(), pageUtils.getiPageSize());

			/************************************************
			 * 返回结果设定
			 ************************************************/
			Long total = ((Page<Map<String, Object>>) list).getTotal();
			list = PropertyUtils.turnToEntity(list);
			map.put("errCode", 0);
			map.put("errInfo", "ok");
			map.put("pageEntity", list);
			map.put("pageSize", pageUtils.getiPageSize());
			map.put("pageNum", pageUtils.getiPageIndex());
			map.put("total", total);
			logger.info(pageUtils.getBaseSession().getLoginName() + "在"
					+ pageUtils.getBaseSession().getLoginName() + new Date()
					+ "查询实体成功");

		} catch (AppBizException e) {
			map.put("errCode", e.getCode());
			map.put("errInfo", e.getMessage());
		}
		return Response.ok(map).build();
	}

	@Override
	public Response getPropFeeReceiptInfo(HttpServletRequest servletRequest,
			Map<String, Object> propFeeReceipt) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeReceipt == null || propFeeReceipt.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			List<Map<String, Object>> list = PropertyUtils
					.turnToEntity(propFeeReceiptService
							.getMonthReDetail(propFeeReceipt));
			if (list != null && list.size() > 0) {
				for (Map<String, Object> ma : list) {
					if (map.get("feePrice") != null) {
						map.put("feePrice", getMoney(map.get("feePrice")
								.toString()));
					}
					if (map.get("amount") != null) {
						map.put("amount",
								getMoney(map.get("amount").toString()));
					}
					String month[] = ma.get("month").toString().split(",");
					Arrays.sort(month);
					if (month.length == 1) {
						ma.put("month", month[0]);
						ma.put("monthTime", "1");
					} else if (month.length > 1) {

						/***
						 * 判断月份是否连续
						 */
						if (isSeriesArray(month)) {
							ma.put("month", month[0] + " - "
									+ month[month.length - 1]);
							ma.put("monthTime",
									getMonthSpace(month[0],
											month[month.length - 1]));
						} else {
							throw new AppBizException(2, "亲，请选择连续的月份");
							/*
							 * if (month.length > 2) { throw new
							 * AppBizException(2, "亲，请选择少于3个月份信息"); }
							 * 
							 * StringBuffer buffer = new StringBuffer(); for
							 * (int i = 0; i < month.length - 1; i++) {
							 * buffer.append(month[i]).append(","); }
							 * buffer.append(month[month.length - 1]);
							 * ma.put("month", buffer.toString());
							 * ma.put("monthTime", month.length);
							 */

						}

					}
				}
			}
			map.put("pageEntity", list);
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	/***
	 * 判断是否连续
	 * 
	 * @param month
	 * @return
	 */
	public static boolean isSeriesArray(String[] month) {
		boolean isSer = false;
		try {
			int monthLength = getMonthSpace(month[0], month[month.length - 1]);
			if (String.valueOf(monthLength)
					.equals(String.valueOf(month.length))) {
				isSer = true;
			}
		} catch (Exception e) {

		}
		return isSer;
	}

	/**
	 * 
	 * @param date1
	 *            <String>
	 * @param date2
	 *            <String>
	 * @return int
	 * @throws ParseException
	 */
	public static int getMonthSpace(String date1, String date2)
			throws ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();

		c1.setTime(sdf.parse(date1));
		c2.setTime(sdf.parse(date2));

		int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);

		// 开始日期若小月结束日期
		if (year < 0) {
			year = -year;
			return year * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH)
					+ 1;
		}

		return year * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH) + 1;

	}

	public static String getAddMonth(String date1, int month)
			throws ParseException {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
		Date d1 = df.parse(date1);
		System.out.println("d1==" + df.format(d1));
		Calendar g = Calendar.getInstance();
		g.setTime(d1);
		g.add(Calendar.MONTH, 1);
		Date d2 = g.getTime();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");

		return simpleDateFormat.format(d2);

	}

	public static void main(String[] args) throws ParseException {
		String month[] = { "2016-06", "2016-07", "2016-08", "2016-09",
				"2016-10", "2016-11", "2016-12", "2017-01", "2017-02",
				"2017-06", "2017-07", "2017-09", "2017-10", };
		Arrays.sort(month);

		List<List<String>> result = split(Arrays.asList(month));

		for (List<String> list : result) {
			System.out.println(list);
		}
		System.out.println(result.size());
		System.out.println(isSeriesArray(month));

	}

	public static List<List<String>> split(List<String> data)
			throws ParseException {
		String datas[] = (String[]) data.toArray(new String[data.size()]);
		Arrays.sort(datas);

		data = java.util.Arrays.asList(datas);
		List<List<String>> result = new ArrayList<List<String>>();
		List<String> group = null;
		for (String value : data) {
			if (group == null
					|| !getAddMonth(group.get(group.size() - 1), 1).equals(
							value)) {
				group = new ArrayList<String>();
				result.add(group);
			}
			group.add(value);
		}
		return result;
	}

	public static List<List<Map<String, Object>>> split(
			List<Map<String, Object>> data, String key) throws ParseException {

		List<List<Map<String, Object>>> result = new ArrayList<List<Map<String, Object>>>();
		List<Map<String, Object>> group = null;
		for (Map<String, Object> value : data) {
			if (group == null
					|| !group.get(group.size() - 1).get(key).toString()
							.equals(value.get(key).toString())) {
				group = new ArrayList<Map<String, Object>>();
				result.add(group);
			}
			group.add(value);
		}
		return result;
	}

	@Override
	public Response editPayWay(HttpServletRequest servletRequest,
			PropFeeReceiptDto propFeeReceipt) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		if (StringUtils.isBlank(propFeeReceipt.getType())) {
			throw new AppBizException(2, "类型信息");
		}

		if (StringUtils.isBlank(propFeeReceipt.getLinkID())) {
			throw new AppBizException(2, "修改信息");
		}
		if (StringUtils.isBlank(propFeeReceipt.getPayType())) {
			throw new AppBizException(2, "支付信息");
		}
		propFeeReceipt.setCreateuserID(pageUtils.getBaseSession().getUserID());
		propFeeReceipt.setDrawer(StringUtils.isBlank(pageUtils.getBaseSession()
				.getTrueName()) ? pageUtils.getBaseSession().getLoginName()
				: pageUtils.getBaseSession().getTrueName());
		propFeeReceipt.setCreateuser(StringUtils.isBlank(pageUtils
				.getBaseSession().getTrueName()) ? pageUtils.getBaseSession()
				.getLoginName() : pageUtils.getBaseSession().getTrueName());
		propFeeReceipt.setPmID(pageUtils.getBaseSession().getPmID());
		propFeeReceipt.setAccessToken(pageUtils.getBaseSession().getKey());
		propFeeReceiptService.editPayWay(propFeeReceipt);
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "修改成功");
		return this.normalResp(propFeeReceipt);
	}

	public String getMoney(String money) {
		String result = "";
		try {
			BigDecimal bd = new BigDecimal(money);
			bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
			result = bd.toString();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return result;

	}

	@Override
	public Response getReceiptNum(HttpServletRequest servletRequest,
			String commID, String pmID, String search, String tsCreate,
			String pageIndex, String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pmID", pmID);
		map.put("commID", commID);
		map.put("search", search);
		List<Map<String, Object>> list = propFeeReceiptService
				.findHasUseReceiptNum(map, pageUtils.getiPageIndex(),
						pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response invalidReceipt(HttpServletRequest servletRequest,
			PropFeeReceiptDto propFeeReceipt) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		propFeeReceipt.setEdituserID(pageUtils.getBaseSession().getUserID());
		propFeeReceipt.setEdituser(StringUtils.isBlank(pageUtils
				.getBaseSession().getTrueName()) ? pageUtils.getBaseSession()
				.getLoginName() : pageUtils.getBaseSession().getTrueName());
		propFeeReceipt.setPmID(pageUtils.getBaseSession().getPmID());
		propFeeReceipt.setAccessToken(pageUtils.getBaseSession().getKey());
		Map<String, Object> result = propFeeReceiptService
				.invalidReceipt(propFeeReceipt);

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		return this.normalResp(result);

	}

	public static double getMax(Double[] doubles) {

		if (doubles == null || doubles.length <= 0) {
			return 0;
		}
		double max = doubles[0];
		for (int i = 1; i < doubles.length; i++) {
			if (doubles[i] > max) {
				max = doubles[i];
			}
		}
		return max;
	}

	@Override
	public Response receiptDetails(HttpServletRequest servletRequest,
			Map<String, Object> propFeeReceipt) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeReceipt == null || propFeeReceipt.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}
			List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> list = PropertyUtils
					.turnToEntity(feeDetailService
							.findropFeeDetailByMap(propFeeReceipt));

			propFeeReceipt.put("status", "1");
			List<Map<String, Object>> offsetInfo = PropertyUtils
					.turnToEntity(propFeeOffsetInfoService
							.bauthfindPropFeeOffset(propFeeReceipt));
			if (list != null && list.size() > 0) {
				/***
				 * 根据费用类目分组
				 */
				List<List<Map<String, Object>>> reInfos = split(list,
						"feeTypeID");
				for (List<Map<String, Object>> reInfo : reInfos) {
					List<String> feeDates = new ArrayList<String>();
					/**
					 * 获取月份
					 */
					for (Map<String, Object> ma : reInfo) {
						feeDates.add(ma.get("feeDate").toString());
					}
					/***
					 * 获取连续的鱼粉分组
					 */
					List<List<String>> rFeeDates = split(feeDates);
					for (List<String> li : rFeeDates) {
						List<Double> feePrices = new ArrayList<Double>();
						String feeTypeName = "";
						/***
						 * 更具月份获取相关的费用信
						 */
						List<Map<String, Object>> lastRe = new ArrayList<Map<String, Object>>();
						for (int i = 0; i < li.size(); i++) {
							for (Map<String, Object> ma : reInfo) {
								if (li.get(i).equals(
										ma.get("feeDate").toString())) {
									lastRe.add(ma);
								}
							}
						}
						/***
						 * 获取费用总额
						 */
						BigDecimal sumMoney = new BigDecimal("0");
						BigDecimal sumAmount = new BigDecimal("0");
						String amount="";
						Map<String, Object> r = new HashMap<String, Object>();
						for (Map<String, Object> ma : lastRe) {
							feeTypeName = ma.get("feeTypeName").toString();
							r.put("feeTypeName", feeTypeName);


							sumMoney = sumMoney.add(new BigDecimal(ma.get(
									"amount").toString()));
							if(ma.get("feeAmount")!=null&&!"".equals(String.valueOf(ma.get(
									"feeAmount")))&&!"0".equals(String.valueOf(ma.get("feeType")))) {
								sumAmount = sumAmount.add(new BigDecimal(ma.get(
										"feeAmount").toString()));
								amount = String.valueOf(sumAmount);
							}

							if(ma.get("feeAmount")!=null&&!"".equals(String.valueOf(ma.get(
									"feeAmount")))&&"0".equals(String.valueOf(ma.get("feeType")))){
								amount=ma.get("feeAmount").toString();
							}


							if (ma.get("feePrice") != null)
								if (!StringUtils.isBlank(ma.get("feePrice")
										.toString())) {
									feePrices.add(Double.parseDouble(ma.get(
											"feePrice").toString()));
								}
						}
						/***
						 * 获取最大的单价
						 */
						double maxFeePrice = getMax((Double[]) feePrices
								.toArray(new Double[feePrices.size()]));

						if (maxFeePrice > 0) {
							r.put("feePrice", maxFeePrice);
						} else {
							r.put("feePrice", "");
						}
						r.put("amount", sumMoney);

						r.put("feeAmount", amount);

						if (li.size() == 1) {
							r.put("monthTime", 1);
							r.put("month", li.get(0));
						}
						if (li.size() > 1) {
							r.put("monthTime", li.size());
							r.put("month",
									li.get(0) + "-" + li.get(li.size() - 1));
						}
						result.add(r);
					}
				}
			}
			Map<String, Object> entity = new HashMap<String, Object>();
			if (offsetInfo != null && offsetInfo.size() > 0) {
				List<String> offsetIDs = new ArrayList<String>();
				for (Map<String, Object> m : offsetInfo) {
					offsetIDs.add(m.get("offsetID").toString());
				}
				entity.put("offsetIDs", offsetIDs);
			}
			map.put("entity", entity);
			map.put("pageEntity", result);
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response receiptDetail(HttpServletRequest servletRequest,
			Map<String, Object> propFeeReceipt) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeReceipt == null || propFeeReceipt.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils
					.turnToEntity(propFeeReceiptService
							.bauthpropFeeReceipt(propFeeReceipt)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response hasOpenPreReceipt(HttpServletRequest servletRequest,
			Map<String, Object> propFeeReceipt) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeReceipt == null || propFeeReceipt.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}
			List<Map<String, Object>> results = PropertyUtils
					.turnToEntity(propFeeOffsetInfoService
							.findOffCount(propFeeReceipt));
			List<Map<String, Object>> reCounts = PropertyUtils
					.turnToEntity(propFeeOffsetInfoService
							.findRectCount(propFeeReceipt));
			for (Map<String, Object> m : results) {
				m.put("isComplete", "false");
				if (reCounts != null && reCounts.size() > 0)
					for (Map<String, Object> r : reCounts) {
						if (m.get("preBillID").toString()
								.equals(r.get("preBillID").toString())) {
							if (m.get("count").toString()
									.equals(r.get("count").toString())) {
								m.put("isComplete", "true");
							}
						}
					}
			}
			map.put("pageEntity", results);
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}
}
